<script setup lang="ts">
import { computed, onMounted, onUnmounted, watch, ref } from 'vue'
import Echarts from '../ReCharts/index.vue'
import { getHKConnectFunds } from '../api/api'
import { isEqual } from 'lodash'

interface Fund {
  sector_name: string
  balance: number
  quota: number
  net_inflow: number
}

const echartsRef = ref()

const data = ref<Fund[]>([])

// 获取最大值
const max = computed(() => {
  let max = 0
  data.value.forEach((item) => {
    if (item.quota > max) {
      max = item.quota
    }
    if (item.balance > max) {
      max = item.balance
    }
  })
  return Math.ceil(max / 500) * 500 * 1.05
})
//获取间隔
const interval = computed(() => {
  let temp_interval = max.value / 1.05
  return temp_interval / 5
})

const stockName = computed(() => {
  return data.value.map((item) => item.sector_name)
})

const limitUp = computed(() => {
  return data.value.map((item) => item.net_inflow + item.balance)
})

const balance = computed(() => {
  return data.value.map((item) => item.balance)
})

const option = computed(() => {
  return {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow', // line shadow none cross
        label: {
          show: false,
        },
      },
      formatter: function (params) {
        // 获取当前柱子的索引
        const index = params[0].dataIndex
        // 获取相应的数据信息
        const stockData = data.value[index]
        // 返回自定义的提示框内容
        return `
        <div>
          <p><strong>股票名称:</strong> ${stockData.sector_name}</p>
          <p><strong>当日资金限额:</strong> ${(
            stockData.balance + stockData.net_inflow
          ).toFixed(2)}<strong> 亿元</strong></p>
          <p><strong>当日资金余额:</strong> ${
            stockData.balance
          }<strong> 亿元</strong></p>
        </div>
      `
      },
      backgroundColor: 'rgba(50, 50, 50, 0.7)', // 提示框背景色
      borderColor: '#333', // 提示框边框颜色
      borderWidth: 1, // 提示框边框宽度
      textStyle: {
        color: '#fff', // 提示框文字颜色
        fontSize: 14, // 提示框文字大小
      },
    },
    grid: {
      left: '10%',
      top: '11%',
      bottom: '15%',
    },
    xAxis: {
      data: stockName.value,
      axisLine: {
        show: true, //显示X轴轴线
        lineStyle: {
          color: '#024d90',
          width: 1,
        },
      },
      axisTick: {
        show: true, //显示X轴刻度
        alignWithLabel: true,
      },
      axisLabel: {
        show: true,
        color: '#a1c2d8', //X轴文字颜色
        fontSize: 14,
      },
    },
    yAxis: [
      {
        type: 'value',
        name: '亿元',
        nameGap: 5,
        nameTextStyle: {
          color: '#8c8d91',
          fontSize: 14,
        },
        splitLine: {
          show: true,
          lineStyle: {
            width: 1,
            color: [
              '#182751',
              '#182751',
              '#182751',
              '#182751',
              '#182751',
              '#182751',
              '#05174d',
            ],
            type: 'dashed',
          },
        },
        axisTick: {
          show: false,
        },
        axisLine: {
          show: true,
          lineStyle: {
            color: '#024d90',
          },
        },
        axisLabel: {
          show: true,
          color: '#8c8d91',
          fontSize: 14,
          showMaxLabel: false,
        },
        min: 0,
        max: max.value,
        interval: interval.value,
      },
    ],
    series: [
      {
        name: '昨日总人数',
        type: 'bar',
        barWidth: 35,
        itemStyle: {
          color: {
            type: 'linear',
            x: 0, // 右
            y: 1, // 下
            x2: 0, // 左
            y2: 0, // 上
            colorStops: [
              {
                offset: 0,
                color: '#3D90FF', // 0% 处的颜色
              },
              {
                offset: 1,
                color: '#3D90FF', // 100% 处的颜色
              },
            ],
          },
        },
        data: balance.value,
        markPoint: {
          symbol: 'rect',
          symbolSize: [50, 2], // 短横线的宽度和高度
          itemStyle: {
            color: '#d53d43',
          },
          emphasis: {
            // 删除高亮时样式
            disabled: true,
          },
          data: [
            {
              name: 'A 标线',
              coord: [0, limitUp.value[0]],
              value: 'A',
              label: { show: false },
            },
            {
              name: 'B 标线',
              coord: [1, limitUp.value[1]],
              value: 'B',
              label: { show: false },
            },
            {
              name: 'C 标线',
              coord: [2, limitUp.value[2]],
              value: 'C',
              label: { show: false },
            },
            {
              name: 'D 标线',
              coord: [3, limitUp.value[3]],
              value: 'D',
              label: { show: false },
            },
          ],
        },
      },
    ],
  }
})

const initEcharts = () => {
  echartsRef.value.initChart()
}

const getData = async () => {
  await getHKConnectFunds()
    .then((res) => {
      if (res && res.data && res.data.status === 'success') {
        let funds = res.data.data
        if (!isEqual(funds, data.value)) {
          data.value = funds
        }
      } else {
        console.error('Error: API response was not successful.')
      }
    })
    .catch((error) => {
      console.error('Error fetching HK Connect funds:', error)
    })
}

watch(data, () => {
  initEcharts()
})

onMounted(async () => {
  await getData()
  initEcharts()
  const interval = setInterval(async () => {
    await getData()
  }, 600000)
  onUnmounted(() => {
    clearInterval(interval)
  })
})
</script>

<template>
  <div class="card">
    <div class="card_content">
      <div class="card_title">
        <span>港股通资金流</span>
      </div>
      <div style="width: 80%; height: 77%; margin-left: 15%">
        <Echarts ref="echartsRef" :option="option" />
      </div>
      <div class="bottom">
        <span class="title">资金净流入(亿元)</span>
        <span
          v-for="item in data"
          :class="{
            increase: item.net_inflow >= 0,
            decrease: item.net_inflow < 0,
          }"
          >{{ item.net_inflow === 0 ? '暂未收盘' : item.net_inflow }}</span
        >
      </div>
    </div>
    <div class="card_background">
      <span></span>
      <span></span>
      <span></span>
      <span></span>
    </div>
  </div>
</template>

<style scoped>
.card {
  width: 59%;
  height: 47%;
  margin: 1%;
}

.bottom {
  display: flex;
  width: 85%;
  height: 9%;
  margin-left: 2%;
}

.title {
  display: grid;
  height: 100%;
  width: 25.5%;
  place-items: center;
  text-align: center;
  background-color: #0e2257;
  color: #8dcbf1;
  font-family: '微软黑体';
  font-size: 15px;
  margin-right: 1px;
}

.increase,
.decrease {
  display: grid;
  height: 100%;
  width: 19.5%;
  place-items: center;
  text-align: center;
  box-sizing: border-box;
  margin-left: 2px;
  margin-right: 2px;
  font-family: '正楷';
  font-size: 16px;
  font-weight: bold;
}

.increase {
  background-color: #0e2257;
  color: #8dcbf1;
}

.decrease {
  background-color: #241a4b;
  color: #ff4c4d;
}
</style>
